﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

namespace QuaManSys.OuterInfo
{
    public partial class OuterInfoRegistA : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            lblQuaInfoProNo.Text = getOutQuaInfo();
            fdbktime.Attributes.Add("ReadOnly", "True");
            lblCusRT.Attributes.Add("ReadOnly", "True");
            txtProDL.Attributes.Add("ReadOnly", "True");
            txtKeyWords.Attributes.Add("ReadOnly", "True");

            if (!IsPostBack)
            {
                initddlProNo();          //工程编号下拉框
                initResponDept();        //责任部门下拉框
                initRelatedDept();       //关注部门复选框 
                ProcssComd.SelectedIndex = 0;
                CareLevel.SelectedIndex = 0;
                CustmReq.SelectedIndex = 0;
                InfoCls.SelectedIndex = 0;
            }
            txtlblMacTyp.Text = CommonInitFunctions.getMachModelNo(ddlProNo.Text);
            txtlblMacNo.Text = CommonInitFunctions.getMachineNo(ddlProNo.Text);
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            if (isValidate())
            {
                insertQualityInfo();
                insertQuaFeedback();
                insertResponsDept();
                Response.Redirect("SubmitSuccess.aspx");
            }
            else
            {
                Response.Redirect("OuterInfoRegist.aspx");
            }

        }

        protected void ddlProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            string projNo = ddlProNo.Text;
            txtlblMacTyp.Text = CommonInitFunctions.getMachModelNo(projNo);
            txtlblMacNo.Text = CommonInitFunctions.getMachineNo(projNo);
        }

        /*
         * multiView的下一步
         */
        protected void nextstep_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 1;
        }

        /*
         * multiView的上一步
         */
        protected void prestep_Click(object sender, EventArgs e)
        {
            MultiView1.ActiveViewIndex = 0;
        }

        #region
        public string maxID()
        {
            var context = new QuaManSysEntities();

            if (context.OuterQualityInfo.Count() != 0)
            {
                var query = from b in context.OuterQualityInfo
                            orderby b.qualityInfoId
                            select b.qualityInfoId;
                return query.Max();
            }
            return "";
        }

        /*
         * 返回外部质量信息号
         */
        private string getOutQuaInfo()
        {
            string ret = "CQI" + "DEPART";                   //TODO: to be fixed, "dept" should replaced with real dept
            string maxid = maxID();
            string dbDateTime = DateTime.Now.Year.ToString();
            if (maxid == "") return ret += dbDateTime + "001";
            string year = maxid.Substring(9, 4);

            if (year != dbDateTime)
            {
                ret += dbDateTime + "001";
            }
            else
            {
                string id = maxid.Substring(13, 3);
                ret += year + (Convert.ToInt16(id) + 1).ToString("000");
            }
            return ret;
        }
        
        /// <summary>
        /// 初始化工程编号下拉框
        /// </summary>
        private void initddlProNo()
        {
            using (var context = new QuaManSysEntities())
            {
                try
                {
                    ddlProNo.Items.Clear();
                    int count = 0;
                    foreach (var item in context.Tab_ProjectNo)
                    {
                        ListItem li = new ListItem(item.projectNo);
                        ddlProNo.Items.Insert(count++, li);
                    }
                    txtlblMacTyp.Text = CommonInitFunctions.getMachModelNo(ddlProNo.Items[0].Text);
                    txtlblMacNo.Text = CommonInitFunctions.getMachineNo(ddlProNo.Items[0].Text);
                }
                catch (EntitySqlException ex)
                {
                    Response.Write("<script>alert('" + ex.ToString() + "')</script>");
                }
            }
        }

        /*
         * 初始化责任部门下拉框选项
         */
        private void initResponDept()
        {
            using (var context = new QuaManSysEntities())
            {
                try
                {
                    ResponDept.Items.Clear();
                    int count = 0;
                    foreach (var item in context.Tab_Department)
                    {
                        ListItem li = new ListItem(item.department);
                        ResponDept.Items.Insert(count++, li);
                    }
                }
                catch (EntitySqlException ex)
                {
                    Response.Write("<script>alert('" + ex.ToString() + "')</script>");
                }
            }
        }

        /*
         * 初始化关注部门复选框选项                  
         */
        private void initRelatedDept()                    
        {
            using (var context = new QuaManSysEntities())
            {
                try
                {
                    cblKeyWords.Items.Clear();
                    int count = 0;
                    foreach (var item in context.Tab_Department)
                    {
                        ListItem li = new ListItem(item.department);
                        cblKeyWords.Items.Insert(count++, li);
                    }
                }
                catch (EntitySqlException ex)
                {
                    Response.Write("<script>alert('" + ex.ToString() + "')</script>");
                }
            }
        }

        /// <summary>
        /// 写质量信息到质量信息表中
        /// </summary>
        private void insertQualityInfo()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                string infoCategory = InfoCls.SelectedIndex.ToString();

                OuterQualityInfo outInfo = new OuterQualityInfo
                {
                    qualityInfoId = lblQuaInfoProNo.Text,
                    projectNo = ddlProNo.Text,
                    components = txtComponent.Text,
                    producer = txtManufac.Text,
                    faultType = txtFaiTyp.Text,
                    projectCategory = txtPjCls.Text,
                    name = txtPjNam.Text,
                    deadline = Convert.ToDateTime(txtProDL.Text),
                    informationCategory = infoCategory,
                    informationSource = txtInfoCla.Text,
                    levelOfImportance = txtImpLev.Text,
                    description = txtInfoDsc.Text,
                    recommendedTreatPlan = txtReqAdv.Text,
                    processingStatus = "分发",
                    processingResults = txtReqRsl.Text,
                    processingAssess = txtProCmm.Text
                };
                context.OuterQualityInfo.Add(outInfo);
                context.SaveChanges();
            }
        }

        /// <summary>
        /// 写反馈表到数据库的反馈表中
        /// </summary>
        private void insertQuaFeedback()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                string subsquReq = CustmReq.SelectedIndex.ToString();
                if (CustmReq.SelectedIndex == 3)
                    subsquReq += "|" + instruction.Text;
                OuterQualityInfoFeedback OutQuaFdbck = new OuterQualityInfoFeedback
                {
                    qualityInfoId = lblQuaInfoProNo.Text,
                    feedbackUnit = lblFdCom.Text,
                    feedbackName = txtFdPer.Text,
                    feedbackTime = Convert.ToDateTime(fdbktime.Text),
                    customerCompany = lblCusCo.Text,
                    relatedParty = lblRelCo.Text,
                    customerName = lblCusNam.Text,
                    customerRole = lblCusRol.Text,
                    customerPhone = lblCusTel.Text,
                    customerReqCloTime = Convert.ToDateTime(lblCusRT.Text),
                    customerAttitude = CareLevel.SelectedIndex.ToString(),
                    cusomerOtherInfo = TextBox4.Text,
                    qualityInfoDes = TextBox2.Text,
                    solutionProposal = TextBox3.Text,
                    subsequentRequest = subsquReq,       
                    processingDemands = ProcssComd.SelectedIndex.ToString()
                };

                context.OuterQualityInfoFeedback.Add(OutQuaFdbck);
                context.SaveChanges();

            }
        }

        /// <summary>
        /// 写责任部门和关注部门到数据库中
        /// </summary>
        private void insertResponsDept()
        {
            using (QuaManSysEntities context = new QuaManSysEntities())
            {
                OuterResponsibleDepart respons = new OuterResponsibleDepart
                {
                    qualityInfoId = lblQuaInfoProNo.Text,
                    isResponDepart = 1,
                    department = ResponDept.Text
                };

                context.OuterResponsibleDepart.Add(respons);
                context.SaveChanges();

                string focString = txtKeyWords.Text;
                if (focString == "") return;//fixed
                string[] focDept = focString.Split('|');

                for (int i = 0; i < focDept.Length; i++)
                {
                    OuterResponsibleDepart focusDept = new OuterResponsibleDepart
                    {
                        qualityInfoId = lblQuaInfoProNo.Text,
                        isResponDepart = 0,
                        department = focDept[i]
                    };
                    context.OuterResponsibleDepart.Add(focusDept);
                    context.SaveChanges();
                }

            }
        }
        #endregion

        bool isValidate()
        {
            if (fdbktime.Text == "") return false;
            if (lblCusRT.Text == "") return false;
            if (txtProDL.Text == "") return false;
            return true;
        }

    }
}